package com.shopping.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.auto.JSONAuthentication;
import com.shopping.entity.ShSalaryEx;
import com.shopping.entity.ShUser;
import com.shopping.mapper.ShSalaryExMapper;
import com.shopping.mapper.ShUserMapper;
import com.shopping.response.Result;
import com.shopping.utils.UpPhotoNameUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author shopping
 * @since 2022-03-09
 */
@RestController
@RequestMapping("/sh-user")
public class ShUserController extends JSONAuthentication {
    @Autowired
    ShUserMapper shUserMapper;
    @Autowired
    ShSalaryExMapper shSalaryExMapper;
    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addUser(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password1, @RequestParam("role") String role, @RequestParam("phone") String phone) throws  Exception{
        ShUser anUser=new ShUser();
        anUser.setUsername(username);
        anUser.setPassword(password1);
        anUser.setRole(role);
        anUser.setPhone(phone);
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("username",anUser.getUsername());
        ShUser a= shUserMapper.selectOne(wrapper);
        if(a!=null){
            Result result=Result.error();
            result.setMessage("该用户已存在");
            this.WriteJSON(request, response, result);
        }else {
            byte[] bytes = file.getBytes();
            String imageFileName = file.getOriginalFilename();
            String fileName = UpPhotoNameUtils.getPhotoName("img",imageFileName);
            Path path = Paths.get("D:\\自己的项目\\流浪动物救助\\adopt\\adopt\\src\\assets\\picture\\" + fileName);
            //“C:\\框架\\D4\\d4_pc_ui\\src\\assets\\images\\img\\”为本地目录
            Files.write(path, bytes);//写入文件
            String avatar_url=fileName;
            anUser.setPicture(avatar_url);
            response.reset();
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            String password= new BCryptPasswordEncoder().encode(anUser.getPassword());
            anUser.setPassword(password);
            System.out.println(password);
            int i=shUserMapper.insert(anUser);
            if(i>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }

    }
    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId ) throws Exception{
        int i=shUserMapper.deleteById(userId);
        if(i>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改电话号码")
    @PostMapping("/updPhone")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id,@RequestParam("phone") String phone)throws Exception{
        ShUser shUser=shUserMapper.selectById(id);
        shUser.setPhone(phone);
        if(shUserMapper.updateById(shUser)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("/updPassword")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("password") String password,@RequestParam("rpassword") String rpassword,@RequestParam("id") int id )throws Exception{
        ShUser shUser=shUserMapper.selectById(id);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        if(encoder.matches(password,shUser.getPassword())){
            String newPassword=new BCryptPasswordEncoder().encode(rpassword);
            shUser.setPassword(newPassword);
            if(shUserMapper.updateById(shUser)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }else{
            Result error = Result.error();
            error.setMessage("密码不正确");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过用户名查找用户")
    @PostMapping("/findByName")
    public void findById(HttpServletRequest request, HttpServletResponse response,@RequestParam("username") String  username,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{

        QueryWrapper wrapper=new QueryWrapper();
        wrapper.like("username",username);
        Page<ShUser> shUserPage=new Page<>(current,size);
        Page<ShUser> shUserPages=shUserMapper.selectPage(shUserPage,wrapper);
        List<ShUser> records = shUserPages.getRecords();
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有用户")
    @PostMapping("/findAllUser")
    public void findById(HttpServletRequest request, HttpServletResponse response,@RequestParam("size") int size,@RequestParam ("current") int current)throws  Exception{
        Page<ShUser> shUserPage=new Page<>(current,size);
        Page<ShUser> shUserPages=shUserMapper.selectPage(shUserPage,null);
        List<ShUser> records = shUserPages.getRecords();
        int total=shUserMapper.selectCount(null);
        if(records.size()>0){
            Result ok = Result.ok().data("userList",records).data("total",total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过id用户")
    @PostMapping("/findByUserId")
    public void findByUserId(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int  id)throws  Exception{
        ShUser shUser=shUserMapper.selectById(id);
        if(shUser!=null){
            Result ok = Result.ok().data("user",shUser);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "发放工资")
    @PostMapping("/setSalary")
    public void setSalary(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int  id,@RequestParam("salary") float salary)throws  Exception{
        ShUser shUser=shUserMapper.selectById(id);
        float sa=shUser.getSalary();
        shUser.setSalary(sa+salary);
        ShSalaryEx shSalaryEx=new ShSalaryEx();
        shSalaryEx.setEmId(id);
        shSalaryEx.setSalary(salary);
        Date date=new Date();
        Timestamp timestamp=new Timestamp(date.getTime());
        shSalaryEx.setCreatTime(timestamp);
        if(shUserMapper.updateById(shUser)>0&&shSalaryExMapper.insert(shSalaryEx)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

}

